#! /bin/bash

# 部署脚本，只需执行一次


function info(){

    echo -e "$@" >&2

    return 0
}

function err(){

    echo -e "\033[31m$@\033[0m" >&2

    return 0
}


if [ ${UID} -ne 0 ];then $(err "无权限执行");exit 0;fi

if [ -s /etc/os-release ];then
    id=$(cat /etc/os-release | grep -E "^ID=" | awk -F= '{print $2}' | head -1 | sed 's|\"||g')
    case ${id} in
        ubuntu)
            G_OSNAME="ubuntu"
            ;;
        tlinux|centos)
            G_OSNAME="centos"
            ;;
        *)
        $(err "不支持本系统")
        exit -1
        ;;
    esac
else
    $(err "不支持本系统")
    exit -1
fi


function ubuntu_install(){

    # 安装软件包
    lists="ppp pppoeconf iperf3 qrencode ethtool ifupdown vlan traceroute"
    for list in ${lists}
    do
        $(info "安装软件：${list}")
        apt-get -y install ${list} > /dev/null 2>&1
        if [ 0 -ne $? ];then $(err "安装 ${list} 失败");fi
    done

	$(info "配置 rc.local ...")

	if [ ! -f "/lib/systemd/system/rc-local.service" ]; then
		$(err "rc-local.service文件不存在，启动rc.local失败。")
		exit -1
	fi

	count=$(cat /lib/systemd/system/rc-local.service | grep "Install" | grep -v "#"| wc -l)
	if [ $count -eq 0 ]; then
		echo >> /lib/systemd/system/rc-local.service
		echo "[Install]" >> /lib/systemd/system/rc-local.service
		echo "WantedBy=multi-user.target" >> /lib/systemd/system/rc-local.service
		echo "Alias=rc-local.service" >> /lib/systemd/system/rc-local.service
	fi

	if [ ! -f "/etc/systemd/system/rc.local.service" ]; then
		ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
	fi

	if [ ! -f "/etc/rc.local" ]; then
		touch /etc/rc.local
		echo "#!""/bin/bash" >> /etc/rc.local
		mkdir -p /etc/rc.d/
		ln -sf /etc/rc.local /etc/rc.d/rc.local
	fi

	chmod +x /etc/rc.local

	systemctl daemon-reload > /dev/null 2>&1
	systemctl start rc-local > /dev/null 2>&1
	systemctl enable rc-local > /dev/null 2>&1

	# ssh 配置
	sed -i "/Port /d" /etc/ssh/sshd_config && echo "Port 36000" >> /etc/ssh/sshd_config
	systemctl restart sshd > /dev/null 2>&1
}

function contos_install(){

    lists="rp-pppoe iperf3 qrencode ethtool traceroute"
    for list in ${lists}
    do
        $(info "安装软件：${list}")
        yum -y install ${list} > /dev/null 2>&1
        if [ 0 -ne $? ];then $(err "安装 ${list} 失败");fi
    done
}

# 设置时区
timedatectl set-timezone Asia/Shanghai

$(${G_OSNAME}_install) || exit -1

wget -q https://gitee.com/KenGe/taihu_install/raw/master/tools/npc_amd64.tar.gz -O npc_amd64.tar.gz
if [ 0 -ne $? ];then $(err "下载错误");exit -1;fi

wget -q https://gitee.com/KenGe/taihu_install/raw/master/tools/taihu -O /usr/sbin/taihu
if [ 0 -ne $? ];then $(err "下载错误");exit -1;fi

mkdir -p /opt/taihu/dl
mv npc_amd64.tar.gz /opt/taihu/dl
taihu update > /dev/null 2>&1

